﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Timers;
using System.Xml;
using System.IO.Ports;
using System.Runtime.InteropServices;


namespace my_english
{
    public partial class Form1 : Form
    {

        [DllImport("user32.dll")]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll")]
        private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        // 定义常量
        private const int SW_HIDE = 0;
        private const int SW_SHOW = 5;

        //Form2 form2;
        public Form1()
        {
            InitializeComponent();
            //form2 = new Form2();
            //form2.TopMost = true;
        }
        
        // 定义文件路径
        string filePath = "./English.txt";//单词记录本
        string fileChoosePath = "./English.ini";
        private static System.Timers.Timer _timer;
        private static DateTime _nextTriggerTime;
        private static System.Timers.Timer _timer1;
        private static DateTime _nextTriggerTime1=DateTime.Now.AddDays(10);
        int number = 0;//单词序列号
        string Mark_read = "";
        string Respond_date="-1";
        DateTime _5min;
        DateTime _30min;
        DateTime _12hour;
        DateTime _1day;
        DateTime _2day;
        DateTime _4day;
        DateTime _7day;


        /// <summary>
        /// 确定学习
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            // 获取当前日期和时间
            DateTime now = DateTime.Now;
            //Console.WriteLine($"当前时间为：{now}");
            
            if (textBox_ying.Text!=""&&textBox_zhong.Text!="")
            {
                number++;
                //_5min = now.AddMilliseconds(10000);
                _5min = now.AddMinutes(5);
                _30min = now.AddMinutes(30);
                _12hour = now.AddHours(12);
                _1day = now.AddDays(1);
                _2day = now.AddDays(2);
                _4day = now.AddDays(4);
                _7day = now.AddDays(7);

                string newData =number.ToString() + "    "+textBox_ying.Text +"    "+textBox_zhong.Text + "    "
                               + _5min + "    " + _30min+"    "+ _12hour + "    " + _1day + "    " + _2day + "    " 
                               + _4day + "    " + _7day+ Environment.NewLine;
                File.AppendAllText(filePath, newData);//向单词本添加
                FileChoose(_5min+","+ _30min + "," + _12hour + "," + _1day + "," + _2day + "," + _4day + "," + _7day , number);//记录时间数据
            }
            Respond_date=Address();
            this.textBox_ying.Text = this.textBox_zhong.Text = "";
            MessageBox.Show("已学习完成！！！", "新单词");
            
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 取消关闭事件
            e.Cancel = true;

            
            this.Hide();
            this.notifyIcon1.Visible = true;
            //this.notifyIcon1.ShowBalloonTip(30, "注意", "大家好，这是一个事例", ToolTipIcon.Info);
            
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
            if (File.Exists(filePath))
            {
                // 文件存在
                //File.AppendAllText(filePath, "NO    单词    中文    5min    30min    12h    1day    2day    4day    7day\n");
                string lastLine = File.ReadLines(filePath).LastOrDefault();
                string[] delimiters = { " ", " ", " ", " " };
                string[] result = lastLine.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
               // Console.WriteLine($"最后一行字符串为: {lastLine}");
                if (lastLine.Length > 0)
                {
                    
                    if (int.TryParse(result[0].ToString(), out int num))
                    {
                        number = num;
                       //Console.WriteLine(num);
                    }
                    else
                    {
                        Console.WriteLine("无法将第一个字符转换为整数");
                    }
                }
               
            }
            else
            {
                // 文件不存在
                File.AppendAllText(filePath, "NO    单词    中文    5min    30min    12h    1day    2day    4day    7day\n");
                File.AppendAllText(fileChoosePath, "!");
                number = 0;
            }
            
            //时钟1配置设置，每天定时
            _timer = new System.Timers.Timer(1000); // 每分钟检查一次
            _timer.Elapsed += TimerElapsed;
            _timer.AutoReset = true;
            _timer.Enabled = true;

            CalculateNextTriggerTime();//启动时调用一次



            //时钟2配置设置，用于定时扫描
            _timer1 = new System.Timers.Timer(1000); // 每分钟检查一次
            _timer1.Elapsed += ReadFile;
            _timer1.AutoReset = true;
            _timer1.Enabled = true;

            Respond_date=Address();//查找合理的响应时间



        }

        //每天定时8点启动
        private static void CalculateNextTriggerTime()
        {
            DateTime now = DateTime.Now;
            DateTime today8am = new DateTime(now.Year, now.Month, now.Day, 8, 0, 0);
            if (now.Hour >= 8&&now.Minute>=0)
            {
                // 如果当前时间已经过了8点，就设置为明天8点
                today8am = today8am.AddDays(1);
            }
            _nextTriggerTime = today8am;
        }

       

        //定时器1响应函数
        private static void TimerElapsed(object sender, ElapsedEventArgs e)
        {
            if (DateTime.Now >= _nextTriggerTime)
            {
                // 这里执行你想要的操作，例如：
                Console.WriteLine($"在 {DateTime.Now} 执行了每天8点的操作");
                CalculateNextTriggerTime();
            }

          
        }

        /// <summary>
        /// 写入定时的时间，时间格式转换
        /// </summary>
        /// <param name="data"></param>
        /// <param name="mark"></param>
        private void FileChoose(string data,int mark)
        {
            /*-------------时间格式转换------------------*/
            //读出时间文件
            string allText = "";
            try
            {
                
                using (StreamReader reader = new StreamReader(fileChoosePath))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        allText += line ;
                    }
                }
                //Console.WriteLine(allText);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Error: {e.Message}");
            }

            string[] allText_S= allText.Split(',');//文本数据
            //Console.WriteLine("----------a" + allText_S[0] + "a--------------");
 
            //把新转进来的时间分割成一个个时间段
            string[] parts = data.Split(',');//要插入的new date
            int flag = 0,flag1;
            string newTime = "";//新的时间数据
            foreach (string part in parts)//以新的数据长度为循环次数
            {
                flag1 = 1;//标志文本数据的尾部

                DateTime time = DateTime.Parse(part);//新时间
                while (allText_S[flag]!="!")//判断文本时间是否到尾部
                {
                    if (allText_S[flag].Length > 2)//分割数据获取时间字符串
                    {
                        DateTime J_time = DateTime.Parse(allText_S[flag].Substring(2));//文本时间
                        //Console.WriteLine(newStr);
                        flag1 = 0;
                        if (J_time>time)
                        {
                            flag1 = 0;
                            newTime = newTime+ mark.ToString() + "."+ time + ".0" + ',';
                       //     Console.WriteLine("----------new:" + newTime + "--------------");
                            //flag++;
                            break;
                        }
                        else
                        {
                            //newTime= newTime+mark.ToString() + "." + J_time + ',';
                            newTime = newTime+ allText_S[flag] + ',';
                         //   Console.WriteLine("----------new:" + newTime + "--------------");
                        }
                    }
                    else
                    {
                        Console.WriteLine("字符串过短，无法获取第二个位置之后的数据");
                    }
                            flag++;
                    
                    if(allText_S[flag] == "!")
                    {
                        flag1 = 1;
                    }
                }

                if(flag1==1)//到达文本尾部直接尾部插入
                {
                    //newTime= newTime + mark.ToString() + "."+ time + ',';
                    newTime = newTime + mark.ToString() + "." + time + ".0" + ',';
                }
                
            }
            newTime = newTime + '!';
          //  Console.WriteLine(flag);
         //   Console.WriteLine("----------new:" +newTime + "--------------");
            File.WriteAllText(fileChoosePath, newTime);
            newTime = "";
        }
  

        bool Time_data=true;

        /// <summary>
        /// 定时二刷新函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ReadFile(object sender, ElapsedEventArgs e)
        {

            if(DateTime.Now >= _nextTriggerTime1)
            if (DateTime.Now >= _nextTriggerTime1)
            {
                Console.WriteLine(_nextTriggerTime1+"--》数据响应！！！！！！！！！！！！！！！");
                //响应数据置一
                string allText = "";
                try
                {

                    using (StreamReader reader = new StreamReader(fileChoosePath))
                    {
                        string line;
                        while ((line = reader.ReadLine()) != null)
                        {
                            allText += line;
                        }
                    }
                    //Console.WriteLine(allText);
                }
                catch (Exception e1)
                {
                    Console.WriteLine($"Error: {e1.Message}");
                }
                string[] read_parts = allText.Split(',');//分割数据
                string new_data = "";
                foreach (string part in read_parts)
                {
                    if (part == Mark_read)
                    {
                        string subStr = part.Substring(0, part.Length - 1)+"1";
                        new_data += subStr + ",";
                        continue;
                    }
                    new_data += part+",";
                }
                File.WriteAllText(fileChoosePath, new_data);

                    if (this.InvokeRequired)
                {
                    this.Invoke(new MethodInvoker(() => 
                    {
                        Time_data=true;
                        Form2 form2 = new Form2();
                        form2.str = this.Respond_date;//str为子类的公有变量
                        form2.Show();
                        //Form2 form3=new Form2();
                        //form3.str = this.Respond_date;//str为子类的公有变量
                        //form3.Show();

                    }));
                }
                else
                {
                    Time_data= true;
                    Form2 form2 = new Form2();
                    form2.str = this.Respond_date;//str为子类的公有变量
                    form2.Show();
                    //Form2 form3 = new Form2();
                    //form3.str = this.Respond_date;//str为子类的公有变量
                    //form3.Show();
                }
                Respond_date =Address();
            }

        }
        
        
        /// <summary>
        /// 查找合理的响应时间
        /// </summary>
        private string Address()
        {
            string allText = "";
            try
            {

                using (StreamReader reader = new StreamReader(fileChoosePath))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        allText += line;
                    }
                }
                //Console.WriteLine(allText);
            }
            catch (Exception e1)
            {
                Console.WriteLine($"Error: {e1.Message}");
            }

            string[] read_parts = allText.Split(',');//分割响应数据          
             string return_data = "";
            // bool oneflag=true;
#if false
            foreach (string part in read_parts)
            {
                // string fixedData = part.Substring(1, 19);
                //             char noeData = part[0];
                //Records = part;//记录该时间
                if (part.Length > 2)
                {
                    string[] Time_period = part.Split('.');//分割响应数据
                    //string newStr = part.Substring(2);
                    DateTime _time = DateTime.Parse(Time_period[1]);
                    //Console.WriteLine("列表时间为：" + _time);
                    if (DateTime.Now < _time)//查找响应的时间点
                    {
                        _nextTriggerTime1 = _time;
                        Console.WriteLine("下次响应时间为：" + _nextTriggerTime1);
                        return part;

                    }


                    //else { _nextTriggerTime1.AddDays(1); }
                    //Console.WriteLine(newStr);
                }
                else
                {


                    DateTime now = DateTime.Now;
                    // now = now.AddMilliseconds(3000);
                    now = now.AddDays(10);
                    _nextTriggerTime1 = now;
                    Console.WriteLine(_nextTriggerTime1 + "已经没有要复习的单词了");
                }
            }
#else
            foreach (string part in read_parts)
            {
                // string fixedData = part.Substring(1, 19);
                //             char noeData = part[0];
                //Records = part;//记录该时间
                if (part.Length > 2)
                {
                    string[] Time_period = part.Split('.');//分割响应数据
                                                            //string newStr = part.Substring(2);
                    DateTime _time = DateTime.Parse(Time_period[1]);
                    //Console.WriteLine("列表时间为：" + _time);
                    if (DateTime.Now < _time)//查找响应的时间点
                    {
                        Time_data = false;
                        Mark_read=part;//响应数据备份
                        _nextTriggerTime1 = _time;
                        Console.WriteLine("下次响应时间为：" + _nextTriggerTime1);
                        return part;

                    }                  
                    else if (Time_period[2]=="0")
                    {
                        Form2 form2 = new Form2();
                        form2.str = part;//str为子类的公有变量
                        form2.Show();
                        //响应数据置一
                        string new_allText = "";
                        foreach (string newpart in read_parts)
                        {
                            if (part==newpart)
                            {                              
                                string subStr = part.Substring(0, part.Length - 1) + "1";
                                new_allText += subStr + ",";
                                continue;
                            }
                            new_allText += newpart + ",";
                        }
                        File.WriteAllText(fileChoosePath, new_allText);
                    }  
                    if(Time_data)
                    {

                    }
                }
                //else
                //{
                //    new_allText += part;
                //}

            }
            //File.WriteAllText(fileChoosePath, new_allText);
            return "-1";
#endif
            return "-1";
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //ReadFile();
            Form2 form2 = new Form2();
            form2.str = this.Respond_date;//str为子类的公有变量
            form2.ShowDialog();
        }

        private void 记单词ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.Visible)
            {
                this.Hide();
            }
            else
            {
                this.Show();
            }
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //this.Close();
            //form2.Close();
            //Application.Exit();
            Environment.Exit(0);
            //Console.WriteLine("关闭");
        }

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            if (this.Visible)
            {
                this.Hide();
            }
            else
            {
                this.Show();
            }
        }
    }
}
